import React, { useEffect, useRef } from 'react';
import { EditorView, lineNumbers } from '@codemirror/view';
import { EditorState } from '@codemirror/state';
import { basicSetup } from 'codemirror';
import { markdown } from '@codemirror/lang-markdown';
import { oneDark } from '@codemirror/theme-one-dark';

interface MarkdownEditorProps {
  content: string;
  onChange: (content: string) => void;
  isDark?: boolean;
  className?: string;
  onImagePaste?: (imageDataUrl: string, fileName: string) => void;
}

export const MarkdownEditor: React.FC<MarkdownEditorProps> = ({
  content,
  onChange,
  isDark = false,
  className = '',
  onImagePaste,
}) => {
  const editorRef = useRef<HTMLDivElement>(null);
  const viewRef = useRef<EditorView | null>(null);

  // 处理图片粘贴
  const handleImagePaste = (file: File) => {
    console.log('handleImagePaste called with:', file.name, file.size, file.type);

    // 检查文件大小（限制为 5MB）
    if (file.size > 5 * 1024 * 1024) {
      alert('图片文件大小超过 5MB，请选择更小的图片');
      return;
    }

    const reader = new FileReader();
    reader.onload = (e) => {
      const dataUrl = e.target?.result as string;
      const fileName = file.name || `image_${Date.now()}.png`;

      console.log('Image converted to dataURL, length:', dataUrl.length);

      // 直接在编辑器中插入图片
      insertImageToEditor(dataUrl, fileName);

      // 如果有回调函数，也通知父组件
      if (onImagePaste) {
        console.log('Calling onImagePaste callback');
        onImagePaste(dataUrl, fileName);
      }
    };

    reader.onerror = (error) => {
      console.error('FileReader error:', error);
      alert('图片读取失败，请重试');
    };

    reader.readAsDataURL(file);
  };

  // 插入图片到编辑器
  const insertImageToEditor = (dataUrl: string, fileName: string) => {
    if (!viewRef.current) {
      console.error('Editor view not available');
      return;
    }

    const view = viewRef.current;
    const cursor = view.state.selection.main.head;
    const imageMarkdown = `![${fileName}](${dataUrl})`;

    console.log('Inserting image at cursor position:', cursor);
    console.log('Image markdown length:', imageMarkdown.length);

    const transaction = view.state.update({
      changes: {
        from: cursor,
        insert: imageMarkdown,
      },
      selection: { anchor: cursor + imageMarkdown.length },
    });

    view.dispatch(transaction);

    // 触发 onChange 回调，通知父组件内容已更改
    const newContent = view.state.doc.toString();
    console.log('New content length after image insert:', newContent.length);
    onChange(newContent);
  };

  useEffect(() => {
    if (!editorRef.current) return;

    // 创建编辑器状态
    const state = EditorState.create({
      doc: content,
      extensions: [
        basicSetup,
        markdown(),
        isDark ? oneDark : [],
        EditorView.updateListener.of((update: any) => {
          if (update.docChanged) {
            const newContent = update.state.doc.toString();
            onChange(newContent);
          }
        }),
        EditorView.theme({
          '&': {
            height: '100%',
            fontSize: '14px',
          },
          '.cm-content': {
            padding: '16px',
            fontFamily: 'Monaco, Menlo, \"Ubuntu Mono\", monospace',
            lineHeight: '1.6',
            whiteSpace: 'nowrap',
          },
          '.cm-focused': {
            outline: 'none',
          },
          '.cm-editor': {
            height: '100%',
          },
          '.cm-scroller': {
            height: '100%',
            overflowX: 'auto',
          },
        }),
      ],
    });

    // 创建编辑器视图
    const view = new EditorView({
      state,
      parent: editorRef.current,
    });

    viewRef.current = view;

    // 添加粘贴事件监听
    const handlePaste = (e: ClipboardEvent) => {
      const items = e.clipboardData?.items;

      if (!items) {
        return;
      }

      // 检查是否有图片
      let hasImage = false;
      for (let i = 0; i < items.length; i++) {
        const item = items[i];

        if (item.type.indexOf('image') !== -1) {
          hasImage = true;
          e.preventDefault();
          e.stopPropagation();

          const file = item.getAsFile();

          if (file) {
            handleImagePaste(file);
          }
          break;
        }
      }

      // 如果处理了图片，阻止事件冒泡
      if (hasImage) {
        return false;
      }
    };

    // 只在编辑器元素上添加监听器，使用 capture 模式优先处理
    const editorElement = editorRef.current;
    editorElement?.addEventListener('paste', handlePaste, { capture: true });

    return () => {
      editorElement?.removeEventListener('paste', handlePaste, { capture: true });
      view.destroy();
      viewRef.current = null;
    };
  }, [isDark]);

  // 当内容从外部更新时同步编辑器
  useEffect(() => {
    if (viewRef.current) {
      const currentContent = viewRef.current.state.doc.toString();
      // 只有当内容真正不同时才更新
      if (content !== currentContent) {
        const transaction = viewRef.current.state.update({
          changes: {
            from: 0,
            to: viewRef.current.state.doc.length,
            insert: content,
          },
        });
        viewRef.current.dispatch(transaction);
      }
    }
  }, [content]);

  return (
    <div
      ref={editorRef}
      className={`h-full w-full ${className}`}
    />
  );
};

export default MarkdownEditor;
